package com.gcloud.controller.dao;

import com.gcloud.controller.entity.MessageTask;
import com.gcloud.controller.enums.MessageTaskStatus;
import com.gcloud.framework.db.dao.impl.JdbcBaseDaoImpl;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;
/**
Copyright (c) [2020] [G-CLOUD TECHNOLOGY] [G-Cloud 8.0] is licensed under the Mulan PSL v1.
You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain
a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN 
"AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.
 */
@Repository
public class MessageTaskDao extends JdbcBaseDaoImpl<MessageTask, String> {

    public int finish(String taskId, MessageTaskStatus status){
        StringBuffer sql = new StringBuffer();

        sql.append("update gc_message_tasks set status = ?, end_time = now() where task_id = ? and status = ?");
        Object[] values = {status.getValue(), taskId, MessageTaskStatus.RUNNING.getValue()};

        return this.jdbcTemplate.update(sql.toString(), values);

    }

    public List<MessageTask> timeoutTask(){
        List<Object> values = new ArrayList<>();
        String sql = "select * from gc_message_tasks t where t.status = ? and t.timeout_time <= now()";
        values.add(MessageTaskStatus.RUNNING.getValue());

        return findBySql(sql, values);
    }

    public void deleteFinishTask(int days){
        StringBuffer sb = new StringBuffer();
        sb.append("delete from gc_message_tasks where to_days(end_time) < to_days(now()) - ?");

        Object[] values = {days};
        this.jdbcTemplate.update(sb.toString(), values);

    }

    public void deleteTask(int days){
        StringBuffer sb = new StringBuffer();
        sb.append("delete from gc_message_tasks where to_days(start_time) < to_days(now()) - ?");

        Object[] values = {days};
        this.jdbcTemplate.update(sb.toString(), values);
    }


}